<template>
  <div class="fileUpload">
    <div class="mains_contain">
      <el-form :inline="true" label-position="left" :model="searchForm" size="small">
        <el-form-item label="租户">
          <el-select v-model="searchForm.tenantId" style="width: 100%" clearable placeholder="请选择">
            <el-option :label="item.name" v-for="item in tenantList" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="文件类型">
          <el-select v-model="searchForm.type" style="width: 100%" clearable placeholder="请选择" @change="changeFile">
            <!-- <el-option value="" label="全部" /> -->
            <el-option v-for="item in typeOptions1" :label="item.label" :key="item.value" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="search" icon="el-icon-search">查询</el-button>
        </el-form-item>
        <el-form-item v-if="searchForm.type != '12'">
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd" v-has="['file:add']" size="mini">文件上传</el-button>
        </el-form-item>
      </el-form>
      <!-- <el-radio-group v-model="type" @change="search" size="small">
      <el-radio-button label="">全部</el-radio-button>
      <el-radio-button v-for="item in typeOptions" :label="item.value" :key="item.value">{{item.label}}</el-radio-button>
    </el-radio-group> -->

      <div class="contant">
        <el-table :data="tableData" style="width: 100%; margin-top: 10px" @selection-change="handleSelectionChange" fit :max-height="maxHeight" border stripe size="mini" highlight-current-row
          :header-cell-style="{ background: '#e5e5e5', color: '#000' }">
          <!-- <el-table-column type="selection" width="40" /> -->
          <el-table-column prop="name" label="名称" width="180" align="center" />
          <el-table-column prop="tenantTxt" label="租户名称" width="80" align="center" />
          <el-table-column prop="url" width="250" label="文件地址" align="center">
            <template slot-scope="{ row }">
              <span v-if="row.url && row.url.length > 30">
                <el-popover placement="top-start" title="" max-width="300" trigger="hover">
                  <div>{{ row.url }}</div>
                  <span slot="reference">
                    {{ row.url.substr(0,30) + '...' }}
                  </span>
                </el-popover>
              </span>
              <span v-else>{{ row.url }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="状态" width="80" align="center">
            <template slot-scope="scope">
              <template v-for="(item, index) in statusOptions">
                <span v-if="item.value == scope.row.status" :key="index">{{
                  item.label
                }}</span>
              </template>
            </template>
          </el-table-column>

          <el-table-column prop="type" label="文件类型" width="100" align="center">
            <template slot-scope="scope">
              <span v-for="(item, index) in typeOptions1" :key="index" :value="item.value" v-show="scope.row.type == item.value">{{ item.label }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="version" label="版本号" width="180" align="center" />
          <el-table-column prop="filesize" label="文件大小" :formatter="fileSizeForMatter" width="80" />
          <!-- <el-table-column prop="filesha256" label="文件SHA256" /> -->
          <el-table-column prop="remark" label="说明" align="center" width="160" />
          <el-table-column prop="createBy" label="创建人" width="160" align="center" />
          <el-table-column prop="createTime" label="创建时间" align="center">
            <template slot-scope="scope">
              {{ scope.row.createTime | formatTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template slot-scope="{ row }">
              <!-- <el-button type="primary" size="mini" @click="handleEdit(row)" icon='el-icon-view'>编辑</el-button> -->
              <el-button size="mini" type="text" style="color: #f56c6c" icon="el-icon-delete" @click="onCanle(row)" v-has="['file:delete']">删除</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="update(row)" v-if="row.type == '2'">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: right">
          <pagination v-show="pagination.total > 0" :limit.sync="pagination.pageSize" :page.sync="pagination.page" :total="pagination.total" @pagination="getPageList" />
        </div>
      </div>
    </div>
    <el-dialog :title="curTitle" :visible.sync="dialogVisible" width="640px" :close-on-click-modal="false" @close="close">
      <el-form ref="addForm" :model="addForm" label-width="80px" size="small" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="addForm.name" clearable />
        </el-form-item>
        <el-form-item label="租户" prop="tenantId">
          <el-select v-model="addForm.tenantId" style="width: 520px" placeholder="请选择">
            <el-option :label="item.name" v-for="item in tenantList" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="说明">
          <el-input type="textarea" v-model="addForm.remark" clearable />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择" style="width: 520px" @change="changeType">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-input type="input" v-model="addForm.version" clearable style="width: 520px" />
        </el-form-item>
        <el-form-item label="原始文件" v-if="!required">
          <el-autocomplete style="width: 520px" v-model="addForm.fileSource1" value-key="value" :fetch-suggestions="querySearchAsync" placeholder="请输入" @select="handleSelect" clearable>
          </el-autocomplete>
        </el-form-item>

        <el-form-item label="目标文件" v-if="!required">
          <el-autocomplete style="width: 520px" v-model="addForm.fileTarget1" :fetch-suggestions="querySearchAsync1" placeholder="请输入" @select="handleSelect1" clearable></el-autocomplete>
        </el-form-item>
        <el-form-item label="文件" v-if="required">
          <!--:data="addForm"-->
          <el-upload class="upload-demo" :multiple="false" :file-list="fileList" ref="upload" :limit="1" accept="*" action="api/v1/file/save" :headers="headers" :data="addForm" :auto-upload="false"
            :on-success="onUploadSuccess" :on-error="onUploadError" :before-upload="beforeUpload" :before-remove="beforeRemove" :on-change="handleChange"
            :disabled="addForm.type == undefined || addForm.type == '33'">
            <el-button size="small" type="primary" @click="uploadList">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <div style="text-align: right">
        <el-button type="primary" @click="submitUpload('addForm')" size="small">保存</el-button>
        <el-button @click="close" size="small">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="" :visible.sync="isLoading" width="200px" :close-on-click-modal="false" :show-close="false" :modal="false" class="lds">
      <loadUpload />
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import * as api from "@/api/link/file";
import * as tenantApi from "@/api/sys/tenant";
import loadUpload from "@/components/uploadLoading.vue"
export default {
  components: {
    loadUpload
  },
  props: {},
  inject: ['reload'],
  data() {
    var rulesValidate = (rule, value, callback) => {

      // let patten =  /^[\u4E00-\u9FA5A-Za-z0-9]+([a-zA-Z0-9]|[~!@$%^&*_.]){0,19}$/
      let patrn = /^[\u4E00-\u9FA5A-Za-z0-9]+([a-zA-Z0-9]|[~!@$%^&*_.]){0,19}$/;
      if (patrn.test(value)) {
        callback();
      } else {
        // this.codebtn1 = true;
        callback(
          new Error("只能是以数字字母或者中文开头,包含特殊字符~!@$%^&*_.等命名")
        );
      }
    };
    return {
      isLoading: false,
      required: true,
      searchForm: {
      },
      tenantList: [],
      type: "",
      state: "",
      fileList: [],
      files: {},
      statusOptions: [
        {
          value: "-1",
          label: "正常",
        },
        {
          value: "0",
          label: "正常",
        },
        {
          value: "1",
          label: "生成中",
        },
        {
          value: "2",
          label: "生成失败",
        },
      ],
      typeOptions1: [
        // 设备软件
        // 补丁
        // 初始化配置
        // shell脚本
        // 组件公钥
        // 容器公钥
        // 应用公钥
        // 容器镜像包
        // 容器升级包
        // 应用文件
        // 终端升级包
        {
          value: "1",
          label: "固件",
        },
        {
          value: "12",
          label: "应用",
        },
        {
          value: "13",
          label: "容器",
        },
        {
          value: "6",
          label: "补丁",
        },
        {
          value: "33",
          label: "差分包",
        },
        {
          value: "2",
          label: "配置文件",
        },


      ],
      typeOptions: [
        // 设备软件
        // 补丁
        // 初始化配置
        // shell脚本
        // 组件公钥
        // 容器公钥
        // 应用公钥
        // 容器镜像包
        // 容器升级包
        // 应用文件
        // 终端升级包
        {
          value: "1",
          label: "固件",
        },
        {
          value: "12",
          label: "应用",
        },
        {
          value: "13",
          label: "容器",
        },
        {
          value: "6",
          label: "补丁",
        },
        // {
        //   value: "12",
        //   label: "配置文件",
        // },
        {
          value: "33",
          label: "差分包",
        },
      ],
      headers: {
        Authorization: getToken(),
      },
      dialogVisible: false,
      multipleSelection: [],
      tableData: [],
      addForm: {
        name: '',
        tenantId: '',
        remark: '',
        version: '',
        fileSource1: '',
        fileTarget1: ''
      },
      pagination: {
        total: 1,
        page: 1,
        pageSize: 10,
      },
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { validator: rulesValidate, trigger: "blur" },
        ],
        version: [
          { required: true, message: "请输入版本号", trigger: "blur" },
          { validator: rulesValidate, trigger: "blur" },
        ],
        type: [{ required: true, message: "请选择类型", trigger: "blur" }],
        tenantId: [
          { required: true, message: "必须选择租户", trigger: "change" },
        ],
        fileSource1: [
          { required: true, message: "请选择原文件", trigger: "blur" },
        ],
        fileTarget1: [
          { required: true, message: "请选择目标文件", trigger: "blur" },
        ],
      },
      curTitle: "新增",
      restaurants: [],
      restaurants1: [],
      timeout: null,
      timeout1: null,
      fileSource: "",
      fileTarget: "",
    };
  },
  computed: {
    maxHeight() {
      var curHeight =
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight;
      return curHeight - 290;
    },
  },
  created() {
    this.getPageList();
    this.getTenantList();

  },
  mounted() {
    //  this.restaurants = this.loadAll();
    this.searchLists(1);
    this.searchLists(2);
  },
  watch: {
    // "addForm.fileTarget1"(val,old) {
    //   if (!val) {
    //     this.fileTarget = "";
    //   }
    // },
    // "addForm.fileSource1"(val) {
    //   if (!val) {
    //     this.fileSource = "";
    //   }
    // },
  },
  filters: {
    typeFilter(type) {
      let res;
      this.typeOptions1.forEach(item => {
        if (item.value == type) {
          res = item.label
        }
      })
      return res
    }
  },
  methods: {
    close() {
      this.files = {}
      this.fileList = []
      if (this.addForm.type != '33' && this.addForm.type != undefined) {
        this.$refs.upload.clearFiles()
      }
      this.$refs.addForm.resetFields();
      this.addForm.remark = ''
      this.addForm.fileTarget1 = ''
      this.addForm.fileSource1 = ''
      setTimeout(() => {
        this.required = true
        this.dialogVisible = false;
      }, 100)

    },
    searchLists(v) {
      let data = {
        type: this.searchForm.type,
        page: 1,
        pageSize: 100,
        name: v == 1 ? this.addForm.fileSource1 : this.addForm.fileTarget1,
      };
      api.page(data).then((res) => {
        console.log('res: ', res);

        let datas = res.data.list;
        if (v == 1) {
          this.restaurants = [];
        } else {
          this.restaurants1 = [];
        }
        datas.forEach((item) => {
          // let type = this.typeFilter(item.type)
          // console.log('type: ', type);
          if (v == 1) {
            this.restaurants.push({ value: item.name, id: item.id });
            let obj = {};
            this.restaurants = this.restaurants.reduce(function (item, next) {

              obj[next.id] ? "" : (obj[next.id] = true && item.push(next));
              return item;
            }, []);
            this.$forceUpdate()


          } else {
            this.restaurants1.push({ value: item.name, id: item.id });
            let obj = {};
            this.restaurants1 = this.restaurants1.reduce(function (item, next) {
              obj[next.id] ? "" : (obj[next.id] = true && item.push(next));
              return item;
            }, []);
            this.$forceUpdate()

          }
        });
        console.log('this.restaurants: ', this.restaurants);
      });
    },
    querySearchAsync(queryString, cb) {
      this.searchLists(1);
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1000 * Math.random());
      // this.$forceUpdate()

    },
    querySearchAsync1(queryString, cb) {
      this.searchLists(2);
      var restaurants = this.restaurants1;
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;
      clearTimeout(this.timeout1);
      this.timeout1 = setTimeout(() => {
        cb(results);

      }, 1000 * Math.random());
      // this.$forceUpdate()
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) > -1
        );
      };
    },
    handleSelect(item) {
      this.fileSource = item.id;
    },
    handleSelect1(item) {
      this.fileTarget = item.id;
    },
    update(row) {
      this.$router.replace({ path: "/configFile", query: { id: row.id } });
    },
    uploadList() {
      if (this.addForm.type == undefined || !this.addForm.type) {
        this.$message({
          type: "warning",
          message: "请选择文件类型!",
        });
        return;
      }
    },
    changeType(val) {
      console.log(typeof val);
      if (val == "33") {
        this.required = false;
      } else {
        this.required = true;
      }
    },
    changeFile(val) { },
    // 获取租户数据
    getTenantList() {
      tenantApi.queryIdNamePair().then((res) => {
        this.tenantList = res.data;
      });
    },
    // 复选框事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getPageList() {
      this.searchList();
    },
    search() {
      this.pagination.page = 1;
      this.searchList();
    },
    searchList() {
      if (this.searchForm.tenantId == "") {
        this.searchForm.tenantId = null;
      }
      const p = Object.assign(
        { type: this.type, page: this.pagination.page, pageSize: this.pagination.pageSize },
        this.searchForm
      );
      api.page(p).then((resp) => {
        this.tableData = resp.data.list;
        this.pagination = resp.data.pagination;
        this.pagination.page = resp.data.pagination.current;
      });
    },
    handleAdd() {
      this.dialogVisible = true;
      this.curTitle = "新增";
    },
    handleEdit(row) {
      this.dialogVisible = true;
      this.curTitle = "编辑";
    },
    onCanle(row) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.deleteById(row.id).then((resp) => {
            if (resp.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              if ((this.pagination.total - 1) % this.pagination.pageSize == 0) {
                if (this.pagination.page > 1) {
                  this.pagination.page = this.pagination.page - 1;
                }
              }
              this.searchList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleDisPacth() {
      this.$router.push("/orderIssued");
    },
    submitUpload(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.required) {
            if (this.files == undefined || !this.files.status || this.files.status == 'fail') {
              return this.$message({
                message: "请上传文件",
                type: "warning",
              });
            } else {
              this.$refs.upload.submit();
              this.isLoading = true
            }
          } else {
            if (!this.fileSource) {
              return this.$message({
                type: "warning",
                message: "输入原始文件不存在!",
              });
            }
            if (!this.fileTarget) {
              return this.$message({
                type: "warning",
                message: "输入目标文件不存在或目标文件为空!",
              });
            }
            if (this.fileSource == this.fileTarget) {
              this.$message({
                type: "warning",
                message: "原文件不能与目标文件相同!",
              });
              return;
            } else {
              delete this.addForm.fileSource1;
              delete this.addForm.fileTarget1;
              let p = Object.assign({}, this.addForm, {
                fileSource: this.fileSource,
                fileTarget: this.fileTarget,
              });
              api.savePatch(p).then((resp) => {
                if (resp.code == 200) {
                  this.$message({
                    type: "success",
                    message: "新增成功!",
                  });
                  this.reload()
                  this.isLoading = false
                  this.addForm = {};
                  this.getPageList();
                  this.$refs.addForm.resetFields();
                  this.dialogVisible = false;
                }
              });
            }
          }
        } else {

          return false;
        }
      });
    },
    beforeRemove(file, fileList) {
      this.files = {}
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleChange(file, list) {
      this.files = file
      this.fileList = list;
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      var testmsg1 = file.name.substring(file.name.lastIndexOf(".", file.name.lastIndexOf(".") - 1) + 1);
      if (this.addForm.type == "12") {
        if (testmsg != "json") {
          this.$message({
            message: "配置文件必须是JSON格式",
            type: "warning",
          });
          this.fileList.pop();
          return;
        }
      } else if (this.addForm.type == "1") {
        if (testmsg != "bin") {
          this.$message({
            message: "后缀必须是bin",
            type: "warning",
          });
          this.fileList.pop();
          return;
        }
      } else if (this.addForm.type == "2") {

        if (testmsg1 != "tar.gz") {
          this.$message({
            message: "后缀必须是tar.gz",
            type: "warning",
          });
          this.fileList.pop();
          return;
        }
      }
      else if (this.addForm.type == "6") {
        if (testmsg != "patch") {
          this.$message({
            message: "后缀必须是patch",
            type: "warning",
          });
          this.fileList.pop();
          return;
        }
      }
    },
    handleRemove(file, fileList) { },
    onUploadSuccess(f) {
      if (f.code === 200) {
        this.$message({
          message: f.message,
          type: "success",
        });
        this.dialogVisible = false;
        this.isLoading = false
        this.files = {}
        this.fileList = []
        this.$refs.upload.clearFiles();
        this.$refs.addForm.resetFields();
        this.addForm.remark = ''
        this.getPageList();
      } else {
        this.fileList[0].status = 'ready'
        this.isLoading = false
        this.$message({
          message: f.message,
          type: "error",
        });
      }
    },
    onUploadError() {
      this.isLoading = false
      this.$message({
        message: "文件上传失败",
        type: "warning",
      });
      return;
    },
    beforeUpload(file) {
      console.log('file: ', file);

    },
    fileSizeForMatter(row, index) {
      var filesize = row.filesize;
      var size = "";
      if (filesize < 0.1 * 1024) {
        //小于0.1KB，则转化成B
        size = filesize.toFixed(2) + "B";
      } else if (filesize < 0.1 * 1024 * 1024) {
        //小于0.1MB，则转化成KB
        size = (filesize / 1024).toFixed(2) + "KB";
      } else if (filesize < 0.1 * 1024 * 1024 * 1024) {
        //小于0.1GB，则转化成MB
        size = (filesize / (1024 * 1024)).toFixed(2) + "MB";
      } else {
        //其他转化成GB
        size = (filesize / (1024 * 1024 * 1024)).toFixed(2) + "GB";
      }
      var sizeStr = size + ""; //转成字符串
      var index = sizeStr.indexOf("."); //获取小数点处的索引
      var dou = sizeStr.substr(index + 1, 2); //获取小数点后两位的值
      if (dou == "00") {
        //判断后两位是否为00，如果是则删除00
        return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2);
      }
      return size;
    },
  },
};
</script>

<style lang="scss">
.fileUpload {
  padding: 20px;

  .curHeader {
    position: relative;
    height: 40px;
    .searcherBox {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
}
.lds {
  .el-dialog {
    box-shadow: 0 0 0 rgba(0, 0, 0, 0.1);
    // background: rgba(0, 0, 0, 0.1);
    height: 150px !important;
    margin-top: 30vh !important;
    .el-dialog__header {
      display: none;
    }
    .el-dialog__body {
      height: 150px;
    }
  }
}
</style>
